package xiang.weiyu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import xiang.weiyu.common.R;
import xiang.weiyu.dto.SetmealDto;
import xiang.weiyu.pojo.Category;
import xiang.weiyu.pojo.Setmeal;
import xiang.weiyu.pojo.SetmealDish;
import xiang.weiyu.service.CategoryService;
import xiang.weiyu.service.SetmealDishService;
import xiang.weiyu.service.SetmealService;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    @Value("${reggie.path}")
    private String path;
    /**
     * 新增套餐
     *
     * @return R<SetmealDto>
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> insert(@RequestBody SetmealDto dto) {
        setmealService.insertSetmeal(dto);
        return R.success("套餐添加成功");
    }

    /**
     * 删除/批量删除
     *
     * @param ids
     * @return R<String>
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> deleteSetmeal(@RequestParam List<Long> ids) {
        //删除存储的图片文件
/*        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        for (Long id : ids) {
            qw.eq(Setmeal::getId, id);
            Setmeal one = setmealService.getOne(qw);
            //获取图片名称
            String image = one.getImage();
            log.info("图片名: " + image);
            //字节流删除本地图片文件
            File file = new File(path + image);
            if (file.exists()) {
                boolean delete = file.delete();
                log.info("文件是否删除: " + delete);
            }
        }*/
        setmealService.deleteWithDish(ids);
        return R.success("套餐删除成功");
    }

    /**
     * 修改
     *
     * @param setmealDto
     * @return R<String>
     */
    @PutMapping
    public R<String> set22meal(@RequestBody SetmealDto setmealDto) {
        setmealService.updateSetmeal(setmealDto);
        return R.success("套餐修改成功");
    }

    /**
     * 修改售卖状态
     *
     * @param status
     * @param ids
     * @return R<String>
     */
    @PostMapping("/status/{status}")
    public R<String> statusDish(@PathVariable Integer status, @RequestParam List<Long> ids) {
        //批量修改状态,停售
        LambdaUpdateWrapper<Setmeal> qw = new LambdaUpdateWrapper<>();
        qw.set(Setmeal::getStatus, status).in(Setmeal::getId, ids);
        setmealService.update(qw);
        //批量修改状态,起售
        for (Long id : ids) {
            Setmeal setmeal = new Setmeal();
            setmeal.setId(id);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        }
        return R.success("状态修改成功");
    }

    /**
     * 修改套餐功能数据回显
     *
     * @param id
     * @return R<Setmeal>
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getSetmealById(@PathVariable Long id) {
        //1、根据套餐id查询套餐数据 select * from setmeal where id =?
        Setmeal setmeal = setmealService.getById(id);

        //2、根据套餐id查询套餐对应的菜品数据 select * from setmeal_dish where setmeal_id = ?
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(qw);

        //3、将套餐 setmeal 和套餐菜品集合 setmealDishList 数据封装到 SetmealDto并返回
        // 3.0 首先new一个SetmealDto对象
        SetmealDto setmealDto = new SetmealDto();
        // 3.1、BeanUtils.copyProperties() 拷贝setmeal到setmealDto中
        BeanUtils.copyProperties(setmeal, setmealDto);
        // 3.2、将setmealDish-List 设置到 setmealDto中
        setmealDto.setSetmealDishes(list);
        //4、返回 setmealDto
        return R.success(setmealDto);
    }

    /**
     * 分页查询套餐
     *
     * @param page
     * @param pageSize
     * @param name
     * @return R<Page>
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        //搜索名称查询
        qw.like(name != null, Setmeal::getName, name);
        //排序
        qw.orderByDesc(Setmeal::getUpdateTime);
        //调用业务层查询
        setmealService.page(pageInfo, qw);

        //此时还缺少套餐分类的名称信息,新建一个泛型为SetmealDto的Page对象
        Page<SetmealDto> pageDto = new Page<>();
        //1.拷贝分页数据,忽略"records"属性(套餐详细数据,因为与SetmealDto的records泛型不同)
        BeanUtils.copyProperties(pageInfo, pageDto, "records");
        //2.通过pageInfo得到Setmeal套餐数据对象
        List<Setmeal> records = pageInfo.getRecords();
        //3.数据流设置SetmealDto的属性,返回SetmealDto集合
        List<SetmealDto> list = records.stream().map((r) -> {
            //创建SetmealDto对象
            SetmealDto setmealDto = new SetmealDto();
            //----设置SetmealDto对象的Setmeal属性(套餐详细数据)
            BeanUtils.copyProperties(r, setmealDto);
            //获取套餐对象的分类管理id
            Long categoryId = r.getCategoryId();
            //通过id调用所关联的分类管理业务层,获取分类管理的对象数据
            Category category = categoryService.getById(categoryId);
            //非空判断
            if (category != null) {
                //获取分类管理的名称
                String categoryName = category.getName();
                //----设置SetmealDto对象的categoryName属性(菜品分类名)
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        pageDto.setRecords(list);
        return R.success(pageDto);
    }

    /**
     * (数据回显)该套餐分类下的套餐
     *
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<Setmeal>> getList(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        qw.eq(setmeal.getStatus() != null, Setmeal::getStatus, 1);
        qw.orderByAsc(Setmeal::getPrice);
        List<Setmeal> list = setmealService.list(qw);
        return R.success(list);
    }
}
